package cn.y.operation.framework.utils.encryption;

/**
 * @ClassName: CRC8Utils
 * @author: 叶子豪
 * @create: 2020-07-20 14:11
 */
public class CRC8Utils {
    private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    private static final byte[] crcTbl;

    static {
        crcTbl = new byte[256];
        byte polynomial = 0x07; // 0x107 x^8
        for (int i = 0; i < 256; i++) {
            byte j = (byte) i;
            for (int k = 0; k < 8; k++) {
                j = (byte) ((j < 0) ? (j << 1) ^ polynomial : j << 1);
            }
            crcTbl[i] = j;
        }
    }

    public static String calcCrc8(byte[] data) {
        byte crcReg = 0;
        for (byte datum : data) {
            crcReg = crcTbl[(crcReg ^ datum) & 0xFF];
        }
        return hexDigits[0xf & (crcReg >> 4)] + "" + hexDigits[crcReg & 0xf];
    }

    public static void main(String[] args) {
        System.out.println(calcCrc8("123SSSSSAHCJ".getBytes()));
    }
}
